<template>
  <div class="app-market-page">
    <!-- 页面头部 -->
    <div class="market-header">
      <div class="header-content">
        <div class="header-title">
          <h1>应用广场</h1>
          <p>发现更多精彩应用，激发无限创意</p>
          <div class="header-decoration">
            <div class="decoration-item"></div>
            <div class="decoration-item"></div>
            <div class="decoration-item"></div>
          </div>
        </div>

        <!-- 搜索框 -->
        <div class="header-search">
          <div class="search-container">
            <SearchOutlined class="search-icon" />
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="搜索应用名称、描述或功能..."
              class="search-input"
              @keydown.enter="handleSearch"
            />
            <button class="search-btn" @click="handleSearch">
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                <path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="search-filter-section">
      <div class="search-container">
        <!-- 筛选条件区域 -->
        <div class="filter-section">
          <!-- 分类筛选 -->
          <div class="filter-group">
            <div class="filter-label">
              <span class="label-text">分类</span>
            </div>
            <div class="filter-buttons">
              <a-button
                v-for="category in categories"
                :key="category.key"
                :type="activeCategory === category.key ? 'primary' : 'default'"
                class="category-btn"
                @click="handleCategoryChange(category.key)"
              >
                <span class="btn-icon">{{ category.icon }}</span>
                <span class="btn-text">{{ category.label }}</span>
              </a-button>
            </div>
          </div>

          <!-- 结果统计和排序 -->
          <div class="filter-controls">
            <div class="results-info">
              <span class="results-count"
                >共 <strong>{{ total }}</strong> 个应用</span
              >
            </div>

            <div class="sort-group">
              <span class="sort-label">排序：</span>
              <a-select
                v-model:value="sortType"
                @change="handleSortChange"
                size="small"
                class="sort-select"
                :bordered="false"
              >
                <a-select-option value="createTime">最新发布</a-select-option>
                <a-select-option value="priority">热门推荐</a-select-option>
              </a-select>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 应用列表区域 -->
    <div class="apps-content">
      <div class="apps-container">
        <!-- 应用网格/列表 -->
        <div v-if="loading" class="loading-container">
          <a-spin size="large" tip="正在加载应用...">
            <div class="loading-placeholder"></div>
          </a-spin>
        </div>

        <div v-else-if="appsList.length === 0" class="empty-state">
          <div class="empty-content">
            <InboxOutlined class="empty-icon" />
            <h3>暂无应用</h3>
            <p>
              {{
                searchKeyword ? '没有找到相关应用，尝试其他关键词' : '还没有应用，快去创建一个吧！'
              }}
            </p>
            <a-button type="primary" @click="goToHome">
              <PlusOutlined />
              创建应用
            </a-button>
          </div>
        </div>

        <!-- 应用网格 -->
        <div v-else class="apps-grid">
          <AppCard v-for="app in appsList" :key="app.id" :app="app" />
        </div>

        <!-- 分页 -->
        <div v-if="total > pageSize" class="pagination-container">
          <a-pagination
            v-model:current="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :show-total="(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
            @change="handlePageChange"
            @showSizeChange="handlePageSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { SearchOutlined, InboxOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { listPublicAppVoByPage } from '@/api/appController'
import AppCard from '@/components/AppCard.vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const appsList = ref<API.AppVO[]>([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const loading = ref(false)

// 搜索和筛选
const searchKeyword = ref('')
const activeCategory = ref('')
const sortType = ref('createTime')

// 分类选项 - 按用户使用场景分类
const categories = [
  { key: '', label: '全部应用', icon: '🌟' },
  { key: '效率工具', label: '效率工具', icon: '⚡' },
  { key: '活动页面', label: '活动页面', icon: '🎉' },
  { key: '网站', label: '网站', icon: '🌐' },
  { key: '娱乐游戏', label: '娱乐游戏', icon: '🎮' },
  { key: '用户应用', label: '用户应用', icon: '👤' },
  { key: '管理平台', label: '管理平台', icon: '⚙️' },
  { key: '数据可视化', label: '数据可视化', icon: '📊' },
  { key: '教育学习', label: '教育学习', icon: '📚' },
  { key: '电商平台', label: '电商平台', icon: '🛒' },
  { key: '社交网络', label: '社交网络', icon: '💬' },
]

// 获取应用列表
const fetchAppsList = async () => {
  try {
    loading.value = true

    const params: API.AppQueryRequest = {
      current: currentPage.value,
      pageSize: pageSize.value,
      appCategory: activeCategory.value,
      sortField: sortType.value,
      sortOrder: 'desc',
    }

    // 添加搜索条件
    if (searchKeyword.value.trim()) {
      params.appName = searchKeyword.value.trim()
    }

    const res = await listPublicAppVoByPage(params)

    if (res.data.code === 0) {
      appsList.value = res.data.data?.records || []
      total.value = res.data.data?.totalRow || 0
    } else {
      message.error('获取应用列表失败：' + res.data.message)
    }
  } catch (error) {
    console.error('获取应用列表失败:', error)
    message.error('获取应用列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchAppsList()
}

// 分类变化处理
const handleCategoryChange = (category: string) => {
  activeCategory.value = category
  currentPage.value = 1
  // 这里可以根据分类筛选，暂时只做UI展示
  fetchAppsList()
}

// 排序变化处理
const handleSortChange = () => {
  currentPage.value = 1
  fetchAppsList()
}

// 分页变化处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchAppsList()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handlePageSizeChange = (current: number, size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchAppsList()
}

// 跳转到首页创建应用
const goToHome = () => {
  router.push('/')
}

// 监听路由查询参数
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.search) {
      searchKeyword.value = newQuery.search as string
    }
    if (newQuery.category) {
      activeCategory.value = newQuery.category as string
    }
  },
  { immediate: true },
)

// 组件挂载时获取应用列表
onMounted(() => {
  fetchAppsList()
})
</script>

<style lang="scss" scoped>
.app-market-page {
  min-height: 100vh;
  background: linear-gradient(to bottom, #ffffff 0%, #f8fafc 100%);
}

.market-header {
  background: linear-gradient(135deg, rgb(135, 151, 232) 0%, rgb(174, 112, 235) 100%);
  color: white;
  padding: 50px 0 50px;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
      radial-gradient(circle at 20% 80%, rgba(135, 151, 232, 0.15) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(174, 112, 235, 0.15) 0%, transparent 50%),
      radial-gradient(circle at 40% 40%, rgba(135, 151, 232, 0.1) 0%, transparent 50%);
  }

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="dots" patternUnits="userSpaceOnUse" width="20" height="20"><circle cx="10" cy="10" r="1" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23dots)"/></svg>');
  }

  .header-content {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 24px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 1;

    .header-title {
      text-align: center;
      margin-bottom: 40px;

      h1 {
        font-size: 2.8rem;
        font-weight: 700;
        margin: 0 0 16px;
        text-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        background: linear-gradient(45deg, #ffffff 30%, #f0f9ff 70%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        letter-spacing: -0.02em;
      }

      p {
        font-size: 1.1rem;
        opacity: 0.95;
        margin: 0 0 20px;
        font-weight: 300;
        letter-spacing: 0.02em;
      }

      .header-decoration {
        display: flex;
        justify-content: center;
        gap: 8px;
        margin-top: 20px;

        .decoration-item {
          width: 30px;
          height: 3px;
          background: linear-gradient(
            90deg,
            transparent 0%,
            rgba(255, 255, 255, 0.8) 50%,
            transparent 100%
          );
          border-radius: 2px;
          animation: pulse 2s ease-in-out infinite;

          &:nth-child(2) {
            animation-delay: 0.3s;
            background: linear-gradient(
              90deg,
              transparent 0%,
              rgba(255, 255, 255, 0.6) 50%,
              transparent 100%
            );
          }

          &:nth-child(3) {
            animation-delay: 0.6s;
            background: linear-gradient(
              90deg,
              transparent 0%,
              rgba(255, 255, 255, 0.4) 50%,
              transparent 100%
            );
          }
        }
      }
    }

    .header-search {
      width: 100%;
      max-width: 600px;

      .search-container {
        position: relative;
        display: flex;
        align-items: center;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 16px;
        padding: 4px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 1);
          box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
          transform: translateY(-2px);
        }

        &:focus-within {
          background: rgba(255, 255, 255, 1);
          box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2);
          transform: translateY(-3px);
        }

        .search-icon {
          position: absolute;
          left: 16px;
          color: #9ca3af;
          font-size: 18px;
          z-index: 2;
          transition: color 0.3s ease;
        }

        .search-input {
          flex: 1;
          height: 48px;
          padding: 0 16px 0 48px;
          border: none;
          background: transparent;
          font-size: 1rem;
          color: #374151;
          outline: none;
          border-radius: 12px;

          &::placeholder {
            color: #9ca3af;
            font-weight: 400;
          }

          &:focus + .search-icon {
            color: #6366f1;
          }
        }

        .search-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
          border: none;
          border-radius: 12px;
          color: white;
          cursor: pointer;
          transition: all 0.3s ease;
          flex-shrink: 0;

          svg {
            transition: transform 0.2s ease;
          }

          &:hover {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            transform: translateX(2px) scale(1.05);
            box-shadow: 0 4px 16px rgba(99, 102, 241, 0.4);

            svg {
              transform: translateX(1px);
            }
          }

          &:active {
            transform: translateX(1px) scale(0.98);
          }
        }
      }
    }
  }

  @keyframes pulse {
    0%,
    100% {
      opacity: 0.4;
      transform: scaleX(1);
    }
    50% {
      opacity: 1;
      transform: scaleX(1.2);
    }
  }
}

.search-filter-section {
  background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
  padding: 0 0 50px;
  margin-top: -40px;
  position: relative;
  z-index: 2;

  .search-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 24px;

    .filter-section {
      background: rgba(255, 255, 255, 0.95);
      border-radius: 32px;
      padding: 40px;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.3);
      margin-top: 40px;

      .filter-group {
        margin-bottom: 32px;

        .filter-label {
          margin-bottom: 20px;

          .label-text {
            font-size: 1.1rem;
            font-weight: 600;
            color: #374151;
            position: relative;

            &::after {
              content: '';
              position: absolute;
              bottom: -8px;
              left: 0;
              width: 30px;
              height: 3px;
              background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
              border-radius: 2px;
            }
          }
        }

        .filter-buttons {
          display: flex;
          gap: 12px;
          flex-wrap: wrap;

          .category-btn {
            border-radius: 20px;
            height: 44px;
            padding: 0 20px;
            font-size: 0.9rem;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
            display: flex;
            align-items: center;
            gap: 8px;

            .btn-icon {
              font-size: 16px;
              line-height: 1;
            }

            .btn-text {
              white-space: nowrap;
            }

            &.ant-btn-primary {
              background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
              border: none;
              box-shadow: 0 4px 16px rgba(99, 102, 241, 0.3);
              transform: translateY(-1px);

              &:hover {
                box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
                transform: translateY(-2px);
              }
            }

            &.ant-btn-default {
              background: rgba(255, 255, 255, 0.9);
              border: 2px solid #e5e7eb;
              color: #6b7280;
              backdrop-filter: blur(10px);

              &:hover {
                background: rgba(255, 255, 255, 1);
                border-color: #6366f1;
                color: #6366f1;
                transform: translateY(-1px);
                box-shadow: 0 4px 16px rgba(99, 102, 241, 0.15);
              }
            }
          }
        }
      }

      .filter-controls {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 20px;

        .sort-group {
          display: flex;
          align-items: center;
          gap: 8px;

          .sort-label {
            font-size: 0.9rem;
            font-weight: 500;
            color: #6b7280;
            white-space: nowrap;
          }

          .sort-select {
            min-width: 100px;

            :deep(.ant-select-selector) {
              background: rgba(99, 102, 241, 0.08) !important;
              border: none !important;
              border-radius: 12px !important;
              height: 32px !important;
              padding: 0 12px !important;
              box-shadow: none !important;
              transition: all 0.3s ease;

              .ant-select-selection-item {
                color: #6366f1 !important;
                font-weight: 500;
                font-size: 0.85rem;
                line-height: 32px !important;
              }
            }

            :deep(.ant-select-arrow) {
              color: #6366f1;
              font-size: 12px;
            }

            &:hover {
              :deep(.ant-select-selector) {
                background: rgba(99, 102, 241, 0.12) !important;
                transform: translateY(-1px);
              }
            }

            &.ant-select-focused {
              :deep(.ant-select-selector) {
                background: rgba(99, 102, 241, 0.15) !important;
                box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2) !important;
              }
            }
          }
        }

        .results-info {
          .results-count {
            font-size: 0.95rem;
            color: #6b7280;
            font-weight: 500;

            strong {
              color: #6366f1;
              font-weight: 700;
            }
          }
        }
      }
    }
  }
}

.apps-content {
  background: linear-gradient(180deg, #f8fafc 0%, #ffffff 100%);
  padding: 0px 0 80px;
  margin-top: -20px;
  position: relative;
  z-index: 1;

  .apps-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 24px;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;

  .loading-placeholder {
    width: 200px;
    height: 100px;
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;

  .empty-content {
    text-align: center;
    color: #9ca3af;

    .empty-icon {
      font-size: 4rem;
      margin-bottom: 24px;
      color: #d1d5db;
    }

    h3 {
      font-size: 1.5rem;
      color: #6b7280;
      margin-bottom: 12px;
    }

    p {
      font-size: 1rem;
      margin-bottom: 24px;
      color: #9ca3af;
    }
  }
}

.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 50px;
  padding: 20px;
  background-color: #ffffff;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 50px;
  padding: 32px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);

  :deep(.ant-pagination) {
    .ant-pagination-item {
      border-radius: 12px;
      border: 2px solid #e5e7eb;
      transition: all 0.3s ease;

      &:hover {
        border-color: #6366f1;
        transform: translateY(-1px);

        a {
          color: #6366f1;
        }
      }
    }

    .ant-pagination-item-active {
      background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
      border-color: #6366f1;
      box-shadow: 0 4px 16px rgba(99, 102, 241, 0.3);
      transform: translateY(-2px);

      a {
        color: white;
        font-weight: 600;
      }
    }

    .ant-pagination-prev,
    .ant-pagination-next {
      border-radius: 12px;
      border: 2px solid #e5e7eb;
      transition: all 0.3s ease;

      &:hover {
        border-color: #6366f1;
        transform: translateY(-1px);

        .ant-pagination-item-link {
          color: #6366f1;
        }
      }
    }

    .ant-pagination-jump-prev,
    .ant-pagination-jump-next {
      border-radius: 12px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .market-header {
    padding: 40px 0 50px;

    .header-content {
      .header-title {
        margin-bottom: 30px;

        h1 {
          font-size: 2.2rem;
        }

        p {
          font-size: 1rem;
        }

        .header-decoration {
          margin-top: 16px;

          .decoration-item {
            width: 25px;
            height: 2px;
          }
        }
      }

      .header-search {
        max-width: 500px;

        .search-container {
          .search-input {
            height: 44px;
            font-size: 0.95rem;
            padding: 0 12px 0 44px;
          }

          .search-icon {
            left: 14px;
            font-size: 16px;
          }

          .search-btn {
            width: 36px;
            height: 36px;
          }
        }
      }
    }
  }

  .search-filter-section {
    padding: 0 0 40px;
    margin-top: -30px;

    .search-container {
      padding: 0 16px;

      .filter-section {
        padding: 30px 24px;
        margin-top: 30px;
        border-radius: 24px;

        .filter-group {
          margin-bottom: 24px;

          .filter-buttons {
            gap: 8px;

            .category-btn {
              height: 38px;
              padding: 0 16px;
              font-size: 0.85rem;

              .btn-icon {
                font-size: 14px;
              }
            }
          }
        }

        .filter-controls {
          flex-direction: column;
          align-items: flex-start;
          gap: 16px;

          .sort-group {
            align-self: flex-end;

            .sort-select {
              min-width: 90px;

              :deep(.ant-select-selector) {
                height: 30px !important;
                font-size: 0.8rem;

                .ant-select-selection-item {
                  line-height: 30px !important;
                  font-size: 0.8rem !important;
                }
              }
            }
          }

          .results-info {
            align-self: center;
          }
        }
      }
    }
  }

  .apps-content {
    padding: 40px 0 40px;
    margin-top: -15px;

    .apps-container {
      padding: 0 16px;
    }
  }

  .apps-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .market-header {
    padding: 30px 0 40px;

    .header-content {
      .header-title {
        margin-bottom: 25px;

        h1 {
          font-size: 1.8rem;
        }

        p {
          font-size: 0.9rem;
        }

        .header-decoration {
          margin-top: 12px;

          .decoration-item {
            width: 20px;
            height: 2px;
          }
        }
      }

      .header-search {
        .search-container {
          padding: 3px;
          border-radius: 14px;

          .search-input {
            height: 40px;
            font-size: 0.9rem;
            padding: 0 8px 0 40px;
          }

          .search-icon {
            left: 12px;
            font-size: 15px;
          }

          .search-btn {
            width: 32px;
            height: 32px;
            border-radius: 10px;

            svg {
              width: 14px;
              height: 14px;
            }
          }
        }
      }
    }
  }

  .search-filter-section {
    .search-container {
      .filter-section {
        padding: 24px 20px;
        margin-top: 25px;
        border-radius: 20px;

        .filter-group {
          margin-bottom: 20px;

          .filter-buttons {
            gap: 6px;

            .category-btn {
              flex: 1;
              min-width: 0;
              height: 36px;
              padding: 0 12px;
              font-size: 0.8rem;

              .btn-icon {
                font-size: 12px;
              }

              .btn-text {
                display: none; // 在小屏幕只显示图标
              }
            }

            // 保留重要分类的文字
            .category-btn:nth-child(1),
            .category-btn:nth-child(2) {
              .btn-text {
                display: inline;
              }
            }
          }
        }

        .filter-controls {
          .sort-group {
            .sort-select {
              min-width: 80px;

              :deep(.ant-select-selector) {
                height: 28px !important;
                padding: 0 8px !important;

                .ant-select-selection-item {
                  line-height: 28px !important;
                  font-size: 0.75rem !important;
                }
              }

              :deep(.ant-select-arrow) {
                font-size: 10px;
              }
            }
          }
        }
      }
    }
  }

  .apps-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
}
</style>
